package com.incar.chuxing.api;

import android.content.Intent;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.activity.personal.LoginActivity;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.utils.Logger;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ApiStore {
    private static ApiStore instance = null;
    private static Retrofit retrofit;

    private ApiStore() {
    }

    public static ApiStore getInstance() {
        if (instance == null) {
            synchronized (ApiStore.class) {
                if (instance == null) {
                    instance = new ApiStore();
                }
            }
        }
        return instance;
    }

    public ApiService getApiService(String baseUrl) {
        return getRetrofit(baseUrl).create(ApiService.class);
    }

    public ParseApiService getLogApiService(String baseUrl) {
        return getRetrofit(baseUrl).create(ParseApiService.class);
    }

    public Retrofit getRetrofit(String baseUrl) {
        //配置okHttp
        OkHttpClient.Builder builder = new OkHttpClient
                .Builder()
                .readTimeout(120, TimeUnit.SECONDS);

        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder();

            Map<String, String> requestMap = ((MyApplication) MyApplication.getInstance()).getRequestHeaderMap();
            for (String mapKey : requestMap.keySet()) {
                if (requestMap.get(mapKey) != null) {
                    requestBuilder.header(mapKey, requestMap.get(mapKey));
                }
            }
            return chain.proceed(requestBuilder.build());
        });
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> Logger.i("apiMsg", message));
        if (BuildConfig.DEBUG) {    //debug模式
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(MyApplication.chuckInterceptor);
        } else {    //release模式
            logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        }
        builder.addInterceptor(logging);
        builder.addInterceptor(new HttpCodeInterceptor());
        //配置Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .build();

        return retrofit;
    }

    /**
     * java bean 转化json数据  序列化
     * 解析反序列化
     *
     * @return
     */
    public Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()//允许序列化反序列化为null
                .create();
    }

    public class HttpCodeInterceptor implements Interceptor {
        public static final int HTTP_CODE_LOG_OUT = 401;//Token验证失效

        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            if (response.code() == HTTP_CODE_LOG_OUT) {
                Logger.d("退出登录", "Http退出登录");
                //ToastUtils.makeText(MyApplication.getInstance(), "请重新登录", ToastUtils.LENGTH_SHORT).show();
                Intent intent = new Intent(MyApplication.getInstance(), LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MyApplication.getInstance().startActivity(intent);
            }
            return response;
        }

    }
}
